package com.yun.zhong.fu.usercenter.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.yun.zhong.fu.usercenter.annation.CheckLog;
import com.yun.zhong.fu.usercenter.dto.user.JwtTokenRespDTO;
import com.yun.zhong.fu.usercenter.dto.user.LoginRespDTO;
import com.yun.zhong.fu.usercenter.dto.user.UserLoginDTO;
import com.yun.zhong.fu.usercenter.dto.user.UserRespDTO;
import com.yun.zhong.fu.usercenter.entity.User;
import com.yun.zhong.fu.usercenter.jwt.JwtOperator;
import com.yun.zhong.fu.usercenter.service.UserService;
import io.jsonwebtoken.Jwt;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author RenPu
 * @Date 2020/12/28 14:26
 * @Version 1.0
 * @Description:
 **/

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/user")
public class UserController {

    @Value("${server.port}")
    private String port;

    private final UserService userService;

    //注入微信sdk
    private final WxMaService wxMaService;

    //注入jwt工具类
    private final JwtOperator jwtOperator;


    @GetMapping("{id}")
    @CheckLog
    public User byIdUser(@PathVariable Integer id) {
        log.info("目前的端口为：+" + port + "我被访问了O(∩_∩)O哈哈~");

        User user = this.userService.findById(id);
        return user;
    }


    /**
     * 配合测试feign多参数传入的解决方案
     * @param
     * @return
     */
    @GetMapping("/makeToken")
    public String makeToken() {

        Map<String, Object> map = new HashMap<>(3);
        map.put("id", 1);
        map.put("wxNickname", "132132");
        map.put("role", "admin");
        String token = this.jwtOperator.generateToken(map);
        return token;
    }


    /**
     * 配合测试feign多参数传入的解决方案
     *
     * @param user
     * @return
     */
    @GetMapping("/q")
    public User testFeignParamter(User user) {
        return user;
    }


    @PostMapping("/login")
    public LoginRespDTO login(@RequestBody UserLoginDTO userLoginDTO) throws WxErrorException {

        //1:通过微信api获取的code,去验证用户是否已经登录微信
        WxMaJscode2SessionResult sessionInfo = this.wxMaService.getUserService()
                .getSessionInfo(userLoginDTO.getCode());

        String openid = sessionInfo.getOpenid();

        //2：验证当前用户是否已经，登注册此小程序（如果没有注册，就做相应的插入）
        User user = this.userService.login(userLoginDTO, openid);

        //3：如果当前用户已经注册过小程序，就直接颁发token

        Map<String, Object> map = new HashMap<>(3);
        map.put("id", user.getId());
        map.put("wxNickname", user.getWxNickname());
        map.put("role", user.getRoles());
        String token = this.jwtOperator.generateToken(map);

        log.info(
                "用户{}登陆成功，生成token = {}, 有效期到：{}",
                userLoginDTO.getWxNickname(),
                jwtOperator.getExpirationTime()
        );

        //构建响应
        return LoginRespDTO.builder()
                .user(UserRespDTO.builder()
                        .id(user.getId())
                        .avatarUrl(user.getAvatarUrl())
                        .bonus(user.getBonus())
                        .wxNickname(user.getWxNickname())
                        .build()
                ).token(JwtTokenRespDTO.builder()
                        .expirationTime(jwtOperator.getExpirationTime().getTime())
                        .token(token)
                        .build()
                ).build();
    }


}
